package whu.edu.demo.Aspect;


import lombok.Data;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;



@Data
class CountStruct{
    private float minTime = 20000;
    private float avgTime = 0f;
    private float maxTime = 0f;
    private float totalTime = 0;
    private float times = 0;
    private int exceptionTimes = 0;

    public void addExceptionTimes(){
        exceptionTimes++;
    }
    public void count(long time){
        times++;
        if(time> maxTime){
            maxTime = time;
        }
        if(time>0&&time< minTime){
            minTime = time;
        }
        totalTime +=time;
        avgTime = totalTime /times;
    }

    @Override
    public String toString(){
        return "最短运行时间" + minTime + "\n" +
                "最长运行时间" + maxTime + "\n" +
                "平均运行时间" + avgTime + "\n" +
                "抛出错误次数" + exceptionTimes + "\n" +
                "总运行时间" + totalTime + "\n" +
                "总运行次数" + times + "\n";
    }
}
/**
 * @author 86159
 */
@Aspect
@Component
public class AspectCount {

    Map<String, CountStruct> map = new HashMap<>();
    private long begin = 0;

    @Pointcut("execution(public * whu.edu.demo.Fuction.Fuction.* (..))")
    public void countTime() {
    }

    @Around("countTime()")
    public void aroundPointcut(ProceedingJoinPoint jp){
        String sig = jp.getSignature().toString();
        CountStruct countStruct = map.get(sig);
        if (countStruct == null) {
            CountStruct temp = new CountStruct();
            map.put(sig, temp);
        }
        long end = 0;
        try {
            begin = System.nanoTime();
            jp.proceed();
            end = System.nanoTime();
            map.get(sig).count(end - begin);
        } catch (Throwable e) {
            end = System.nanoTime();
            map.get(sig).count(end - begin);
            map.get(sig).addExceptionTimes();
        }

    }

    public void show() {
        for (String c : map.keySet()) {
            System.out.println("函数" + c);
            System.out.println(map.get(c).toString());
        }
    }
}